package com.zmn.oms.task.listener;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.zmn.common.utils.string.StringUtil;
import com.zmn.manager.mq.annotation.AliyunMQHandler;
import com.zmn.manager.mq.annotation.AliyunMQListener;
import com.zmn.manager.mq.constant.MqTagConsts;
import com.zmn.manager.mq.constant.MqTopicConsts;
import com.zmn.oms.business.interfaces.order.OrderBService;
import com.zmn.oms.common.exception.OmsBaseException;
import com.zmn.oms.manager.utils.OmsMqTagConsts;
import com.zmn.oms.zmn.business.interfaces.order.OrderUploadIascBService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Objects;

/**
 * 类描述：工单
 *
 * @author lujia
 * @date 2018/11/30 16:53
 */
@AliyunMQListener(topic = "${spring.mq.topic.oms}")
@Component
public class OrderChangeListener {

    private static final Logger logger = LoggerFactory.getLogger(OrderChangeListener.class);

    @Autowired
    private OrderBService orderBService;

    @Autowired
    private OrderUploadIascBService orderUploadIascBService;


    @AliyunMQHandler(tags = MqTagConsts.ZMN_TOPIC_OMS_CHANGE_ORDER)
    public void orderChange(String message){

        // test
        if (Objects.equals(message, MqTopicConsts.MQ_TEST_MESSAGE)) {
            logger.debug("#mq#order# recive test success");
            return;
        }

        try {
            logger.debug("#mq#orderchange#recive message:{}", message);
            orderBService.syncOrder(Long.valueOf(message));
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
    }

    /**
     * 工单数据同步上传
     *
     * @param message
     */
    @AliyunMQHandler(tags = OmsMqTagConsts.ZMN_TOPIC_OMS_ORDER_WORK_SYNC_CHANGE_UPLOAD_IASC)
    public void orderUploadIasc(String message) {

        logger.debug("#mq#order#syncchangeuploadiasc#recive message:{}", message);
        if (StringUtil.isBlank(message)) {
            return;
        }

        try {
            JSONObject jsonObject = JSON.parseObject(message);

            orderUploadIascBService.addUploadOrderList(Long.valueOf(jsonObject.getString("orderId")),
                    Integer.valueOf(jsonObject.getString("logType")));
        } catch (OmsBaseException obe) {
            logger.error("Handler upload iasc message occur exception,[{}]", obe.getMessage());
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
    }
}
